<script setup lang="ts">
import { buildingAddApi, buildingEditApi } from '@/apis/park'
import type { BuildingI } from '@/types/park'
import { ElMessage } from 'element-plus'
import { ref } from 'vue'

const props = defineProps(['modelValue'])
const emit = defineEmits(['update:model-value', 'success'])
const defaultParams = {
  id: undefined,
  name: '',
  floors: undefined,
  area: undefined,
  propertyFeePrice: undefined,
}
const params = ref<BuildingI>({
  id: undefined,
  name: '',
  floors: undefined,
  area: undefined,
  propertyFeePrice: undefined,
})
const rules = {
  name: [{ required: true, message: '请输入楼宇名称', trigger: 'blur' }],
  floors: [{ required: true, message: '请输入楼层数', trigger: 'blur' }],
  area: [{ required: true, message: '请输入在管面积', trigger: 'blur' }],
  propertyFeePrice: [
    { required: true, message: '请输入物业费', trigger: 'blur' },
  ],
}
const formRef = ref()
const getParams = () => {
  params.value = { ...props.modelValue.params }
}
// 关闭弹层
const closeDialog = () => {
  formRef.value.resetFields()
  emit('update:model-value', {
    params: defaultParams,
    dialogVisible: false,
  })
  params.value = defaultParams
}
// 确定点击事件
const onSubmit = async () => {
  await formRef.value.validate()

  if (params.value.id) {
    await buildingEditApi(params.value)
    ElMessage.success('编辑成功~')
  } else {
    await buildingAddApi(params.value)
    ElMessage.success('添加成功~')
  }

  emit('success')
  closeDialog()
}
</script>

<template>
  <el-dialog
    title="添加楼宇"
    width="35%"
    :model-value="modelValue.dialogVisible"
    @close="closeDialog"
    @open="getParams"
  >
    <el-form
      :model="params"
      :rules="rules"
      ref="formRef"
      style="width: 70%; margin: 10px auto 0 auto"
      label-position="top"
    >
      <el-form-item label="楼宇名称" prop="name">
        <el-input v-model="params.name" placeholder="请输入楼宇名称" />
      </el-form-item>
      <el-form-item label="楼宇层数" prop="floors">
        <el-input
          v-model="params.floors"
          placeholder="请输入楼宇层数"
          type="number"
          :min="1"
        />
      </el-form-item>
      <el-form-item label="在管面积" prop="area">
        <el-input v-model="params.area" placeholder="请输入在管面积">
          <template #append>m²</template>
        </el-input>
      </el-form-item>
      <el-form-item label="楼宇名称" prop="propertyFeePrice">
        <el-input v-model="params.propertyFeePrice" placeholder="请输入物业费">
          <template #append>元/m²</template>
        </el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="closeDialog">取消</el-button>
      <el-button type="primary" @click="onSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.el-form {
  ::v-deep(.el-form-item__label) {
    color: rgb(39, 39, 39);
    font-weight: 500;
  }

  .el-input {
    ::v-deep(.el-input-group__append) {
      color: rgb(59, 59, 59);
    }
  }
}
</style>
